﻿

namespace EasyNet.Solr.Impl
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;

    public class JsonFacetFieldsParser : ISolrResponseParser<string, IDictionary<string, IList<FacetField>>>
    {
        public IDictionary<string, IList<FacetField>> Parse(string result)
        {
            if (result == null)
            {
                return null;
            }

            IDictionary<string, IList<FacetField>> facetFieldsResult = null;
            var bytes = Encoding.UTF8.GetBytes(result);

            using (var reader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max))
            {
                var xmlDoc = XDocument.Load(reader);

                var facetCounts = xmlDoc.Root.Element("facet_counts");

                if (facetCounts == null)
                {
                    return null;
                }

                var facetFields = facetCounts.Element("facet_fields");

                if (facetFields == null)
                {
                    return null;
                }

                facetFieldsResult = new Dictionary<string, IList<FacetField>>(facetFields.Elements().Count());

                foreach (var element in facetFields.Elements())
                {
                    var fieldName = element.Name.LocalName;

                    if (!facetFieldsResult.ContainsKey(fieldName))
                    {
                        facetFieldsResult.Add(fieldName, new List<FacetField>());
                    }

                    var i = 0;

                    foreach (var countElement in element.Elements())
                    {
                        if ((i % 2) == 0)
                        {
                            facetFieldsResult[fieldName].Add(new FacetField() { Name = countElement.Value });
                        }
                        else
                        {
                            facetFieldsResult[fieldName][i >> 1].Count = int.Parse(countElement.Value);
                        }

                        i++;
                    }
                }
            }

            return facetFieldsResult;
        }
    }
}
